<template>
  <div class="subcontract-registration-manage">
    <div class="model-title-css">
      <div>监督检查</div>
      <el-button class="liuchengbtn" style="margin-left:10px;" type="text" @click="processDialog=true">
        <i class="iconfont "></i> 流程示意图
      </el-button>
    </div>
    <el-dialog width="1200px" class="dialog" title="流程示意图" :visible.sync="processDialog" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false">
      <el-image style="display:block;height:600px" class="g-dialog-img" :src="require('@/assets/images/liuchengtu/supervision.png')" alt="" :preview-src-list="[require('@/assets/images/liuchengtu/supervision.png')]" />
    </el-dialog>

    <div class="background_wrap public-flex-row">
      <div class="left-box WholeScroll">
        <el-tree class="Public-Tree-Class" :data="leftList" :props="defaultProps" ref='treeData' node-key="id" :highlight-current='true' :default-expanded-keys="defaultTreeKey" @node-click="handleNodeClick"></el-tree>
      </div>
      <div class="right-box">
        <div class="operate_wrap flex">
          <div class="flex-center">
            <el-button type="primary" size="small" class="add buildButtonStyle" v-permission="permission.add" round @click="showDialog('build', '新增')"><i class="iconfont icon-icon_add"></i> 新增
            </el-button>
          </div>
          <div class="flex-right-action-group">
            <el-select class="select" size="small" @change="getList(true)" v-model="search.inspectionType" placeholder="选择类型" clearable>
              <el-option v-for="item in inspectionTypeArr" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>

            <el-select class="select" size="small" @change="getList(true)" v-model="search.rectificationStatus" placeholder="选择状态" clearable>
              <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>

            <el-date-picker v-model="search.inspectionTime" value-format="yyyy-MM-dd" type="daterange" style="width:300px;margin-left: 15px;" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="getList(true)">
            </el-date-picker>
            <el-button class="search" size="small" @click="getList(true)">
              <i class="iconfont icon-sousuo"></i>&nbsp;搜索
            </el-button>
          </div>
        </div>
        <!--  -->
        <div class="list_wrap">
          <el-table :border="true" class="" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" @cell-click="cellClick" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
            <el-table-column show-overflow-tooltip prop="xh" label="编号" width="150">
              <template slot-scope="scope">
                {{ scope.row.serialNumber }}
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip prop="inspectionType" label="监督检查类型" width="120">
              <template slot-scope="scope">
                {{inspectionTypeStr[scope.row.inspectionType]?inspectionTypeStr[scope.row.inspectionType]:'' }}
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="责任标段" prop="sectionName" width="140">
              <template slot-scope="scope">
                <div>{{scope.row.sectionName}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="受检单位" prop="buildUnit" width="190">
              <template slot-scope="scope">
                <div>{{scope.row.buildUnit}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="签发时间" width="160" prop="issueTime">
              <template slot-scope="scope">
                <div>{{scope.row.issueTime}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="签发部门" width="110">
              <template slot-scope="scope">
                {{scope.row.creatDept}}
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="通知单" width="80">
              <template slot-scope="scope">
                <div class="table-iconfont-box row-i-hover-css" style=" text-align: center;">
                  <i class="iconfont icon-a-wenjian1" v-if="scope.row.fileList&&scope.row.fileList.length>0" @click="showFiles(scope.row,'通知单')"></i>
                </div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="状态" width="140">
              <template slot-scope="scope">
                <div v-if="scope.row.nodeName" style="text-align: left;" v-html="scope.row.nodeName"></div>
                <div v-else style="text-align: left;">待上报</div>
              </template>
            </el-table-column>

            <!-- <el-table-column show-overflow-tooltip label="状态" width="170">
              <template slot-scope="scope">
                <div v-if="scope.row.nodeName" style="text-align: left;" v-html="scope.row.nodeName"></div>
                <div v-else style="text-align: left;">待上报</div>
              </template>
            </el-table-column> -->

            <el-table-column show-overflow-tooltip label="操作" width="300" fixed="right">
              <template slot-scope="scope">
                <!-- <el-button size="mini" class="menu_icon iconfont icon-icon_look action_color1" v-permission="permission.show" @click="showDialog('check','查看',scope.row.id)">&nbsp;查看</el-button>
                <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="showDialog('edit','编辑',scope.row.id)">&nbsp;修改</el-button>
                <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="showDialog('delete','删除',scope.row.id)">&nbsp;删除</el-button> -->
                <work-flow-btn :row="scope.row" :type="2" @edit="edit" @del="del" @approve="approve" @detail="detail" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="float: right; margin-top: 15px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.total" :current-page="search.pageNo + 1" :prev-text="tablePaginationPrev" :next-text="tablePaginationNext" @current-change="paginationChange">
          </el-pagination>
        </div>
      </div>
    </div>

    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>

    <el-dialog width="600px" class="approveDialog" :visible.sync="showFileDialog" :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-a-wenjian1"></i>
        <span>附件</span>
      </span>
      <el-table :border="true" :header-cell-style="{padding: '0',height:'38px',backgroundColor: '#f2f2f2',textAlign:'center',borderColor: '#d4d4d4'}" :cell-style="{padding: '6px 0',textAlign:'center',borderColor: '#d4d4d4'}" ref="multipleTable" :data="nowFileList" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px;">
        <el-table-column show-overflow-tooltip label="序号" type="index" width="60"></el-table-column>
        <el-table-column show-overflow-tooltip label="文件名" style="text-align: center" width="320">
          <template slot-scope="scope">
            <div style="text-align: center;" v-html="scope.row.name"></div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip min-width="20%" label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light" content="查看" placement="top">
              <div class="menu_icon" @click="viewFile(scope.row.id)" style="display: inline;cursor:pointer;margin-right: 5px"><i class='iconfont icon-icon_look'></i></div>
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="下载" placement="top">
              <div class="menu_icon" @click="dlFile(scope.row)" style="display: inline;cursor:pointer"><i class='iconfont icon-icon-xiazai'></i></div>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <!--新建和编辑的暂存上报-->
        <el-button size="small" @click="showFileDialog=false"><i class="iconfont icon-icon_cancel"></i> 关 闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { tableRowStyleGol, tableCellStyleGol, tableHeaderCellStyleGol, doCreateObject } from '@/utils/publicFun'
import supervisionCheck from '@/api/buss/supervisionCheck'
import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'
import crudDict from "@/api/system/dict";
import WorkFlowBtn from '@/components/WorkFlow/table'
import publicSearchData from '@/mixins/publicSearchData'
export default {
  name: `demo`,
  mixins: [publicSearchData],
  components: {
    WorkFlowBtn,
    Detail: require(`./supervision-detail`).default,
  },
  data() {
    return {
      processDialog: false,
      leftList: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      defaultTreeKey: [],
      permission: {
        add: ['100', '1009158:add'],
        show: ['100', '1009158:show'],
        edit: ['100', '1009158:edit'],
        del: ['100', '1009158:del'],
      },
      inspectionTypeArr: [],
      inspectionTypeStr: {},
      statusList: [
        { name: '整改中', id: '1' },
        { name: '复核中', id: '2' },
        { name: '已延期', id: '3' },
        { name: '已办结', id: '4' },
      ],
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      // list: [{}, {}, {}, {}],
      list: [],
      // 搜索参数
      search: {
        pageNo: 0,
        pageSize: 10,
        rectificationStatus: '',
        extensionStatus: '',
        inspectionTime: '',
        total: 0,
        //
        //pageSum: 0,
        sectionId: '',
        projectId: '',
        sortType: '',
        checkOption: '',
        completeCondition: '',
        inspectionLevel: '',
      },
      //
      publicSearchType: '标段默认选择',
      sectionTree: [],
      chooseTreeData: {},
      hasAdd: false, //是否有新增权限
      loading: false,

      title: '人员',
      addSectionId: '',
      projectTypeArr: [],
      projectStatusArr: [],
      inspectionLevelList: [],

      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      postDetailData2: {
        show: false,
        type: 'import',
        typeNmae: '导入'
      },
      // 向详情子组件的传值
      treeEditDialogData: {
        show: false,
        nowTreeData: []
      },
      fileTitle: '',
      nowFileList: [],
      showFileDialog: false
    }
  },
  mounted() {
    this.initData()
    this.getInspectionLevel()
  },
  methods: {
    //预览
    viewFile(e) {
      this.loading = true
      this.$httpGet('/file-server/file/preview?id=' + e).then(response => {
        this.loading = false;
        //  如果是minio地址路径，则调用kkview
        if (!response.data.startsWith("/")) {
          window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
        } else {
          //  如果是转换后的previewGetFile，浏览器直接打开
          window.open(response.data);
        }
      }).catch(res => {
        console.log(res)
        this.loading = false;
      })
    },
    //下载文件
    dlFile(e) {
      this.$publicUpload.checkFile(e.id, e.name)
    },
    showFiles(row, title) {
      console.log(row, '=============')
      this.fileTitle = title
      this.nowFileList = row.fileList
      if (this.nowFileList) {
        this.showFileDialog = true
      }
    },
    getInspectionLevel() {
      crudDict.getByCode('supervisory_inspection_type').then(res => {
        if (res.code == 200) {
          this.inspectionTypeArr = res.data
          if (res.data.length > 0) {
            res.data.map(e => {
              this.$set(this.inspectionTypeStr, e.id, e.name)
            })
          }
        }
      })
    },
    //  导入excel
    importExcel() {
      this.postDetailData2 = {
        show: true,
        type: 'import',
        typeName: '导入'
      }
      //触发 文件选择的click事件
      // $("#excel-import-button").trigger("click");
    },
    approve(obj) {
      this.postDetailData = {
        show: true,
        type: 'approve',
        typeName: '审核',
        detailId: obj.id,
        search: this.search
      }
    },
    edit(obj) {
      this.postDetailData = {
        show: true,
        type: 'edit',
        typeName: '编辑',
        detailId: obj.id,
        search: this.search
      }
    },
    detail(obj) {
      this.postDetailData = {
        show: true,
        type: 'check',
        typeName: '查看',
        detailId: obj.id,
        search: this.search
      }
    },
    del(obj) {
      if (obj.id === '') {
        msgUtil.error2('请先选择要删除的记录！')
        return
      }
      msgUtil.confirm('确认删除该条数据?').then(res => {
        let idlist = []
        idlist.push(obj.id)
        let param = {
          ids: idlist
        }
        supervisionCheck.del(param).then(res => {
          if (res.code === 200) {
            msgUtil.success2('删除成功!')
            this.getList()
          } else {
            msgUtil.error2(res.data.message)
          }
        })
      })
    },
    initData() {
      projectSectionInfo.getLeftProjectTree().then(res => {
        if (res.code === 200) {
          this.$set(this, 'leftList', res.data)
          this.$nextTick(() => {
            if (this.$headerSearch) {
              if (this.changeHeaderProject) {
                this.leftList.forEach((item, index) => {
                  if (item.id == this.changeHeaderProject) {
                    this.defaultTreeKey.push(this.changeHeaderProject)
                    if (item.hasOwnProperty('children') && item.children.length > 0) {
                      this.$refs['treeData'].setCurrentKey(item.children[0].id);
                      this.handleNodeClick(item.children[0])
                    }
                  }
                })
              } else {
                this.defaultTreeKey.push(this.leftList[0].id)
                if (this.leftList[0].hasOwnProperty('children') && this.leftList[0].children.length > 0) {
                  this.$refs['treeData'].setCurrentKey(this.leftList[0].children[0].id);
                  this.handleNodeClick(this.leftList[0].children[0])
                }
              }
            } else {
              this.defaultTreeKey.push(this.leftList[0].id)
              if (this.leftList[0].hasOwnProperty('children') && this.leftList[0].children.length > 0) {
                this.$refs['treeData'].setCurrentKey(this.leftList[0].children[0].id);
                this.handleNodeClick(this.leftList[0].children[0])
              }
            }
          })
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(() => {
        this.$messageError('获取项目标段树失败')
      })
    },


    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.status === 1) {
            if (callback) callback(res)
            // 重新获取数据
            setTimeout(() => {
              this.getList(true)
            }, 1000)
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    handleNodeClick(data) {
      console.log(data, 'ceshi');
      this.search.projectId = '';
      this.search.sectionId = '';
      if (data.type == 'projectId') {
        this.search.projectId = data.id;
        this.search.projectName = data.name;
      }
      if (data.type == 'sectionId') {
        this.search.sectionId = data.id;
        this.search.sectionName = data.name;
        this.search.projectId = this.getProjectIdBySectionId(this.search.sectionId).id
        this.search.projectName = this.getProjectIdBySectionId(this.search.sectionId).name
        this.addSectionId = data.id;
      }
      this.getList(true)
    },
    getProjectIdBySectionId(sectionId) {
      for (let i in this.leftList) {
        if (this.leftList[i].hasOwnProperty('children') && this.leftList[i].children.length > 0) {
          for (let j in this.leftList[i].children) {
            if (this.leftList[i].children[j].id == sectionId) {
              return this.leftList[i]
            }
          }
        }
      }
    },
    // 格式化表单数据
    formatter(row, column) {
      let array = column.property.split('.')
      let result
      array.forEach((item, i) => {
        result = result === undefined ? row[item] : result[item]
      })
      if (result === '' || result === undefined) {
        return '--'
      } else {
        return result
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      if (column.property === 'protocolNum') {
        this.detail(row)
      } else if (column.property === 'inspectionTime') {
        this.detail(row)
      }
    },
    // 获取列表 api
    getList(reload) {
      if (reload) {
        this.search.pageNo = 0
      }
      this.list = []
      let param = {
        pageNo: this.search.pageNo,
        pageSize: this.search.pageSize,
        projectId: this.search.projectId,
        sectionId: this.search.sectionId,
        date: this.search.date,
        farmerName: this.search.farmerName
      }
      if (this.search.inspectionTime) {
        this.search.startDate = this.search.inspectionTime[0]
        this.search.endDate = this.search.inspectionTime[1]
      } else {
        this.search.startDate = ''
        this.search.endDate = ''
      }
      supervisionCheck.listPage(this.search).then(res => {
        if (res.code == 200) {
          this.list = res.data.content
          this.search.total = res.data.totalElements
        } else {
          msgUtil.error2(res.data.message)
        }
      })


    },

    // 切换列表
    paginationChange(index) {
      this.search.pageNo = index - 1
      this.getList()
    },
    /*  操作 */
    showDialog(type, typeName, detailId) {
      switch (type) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: '',
            search: this.search
          }
          break
        case 'edit':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            search: this.search,
            chooseTreeData: this.chooseTreeData,
          }
          break
        case 'check':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            search: this.search,
            chooseTreeData: this.chooseTreeData
          }
          break
        case 'delete':
          if (detailId === '') {
            msgUtil.error2('请先选择要删除的记录！')
            return
          }
          msgUtil.confirm('确认删除该条数据?').then(res => {
            let idlist = []
            idlist.push(detailId)
            let param = {
              ids: idlist
            }
            supervisionCheck.del(param).then(res => {
              if (res.code === 200) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(res.data.message)
              }
            })
          })
          break
      }
    },




  },
}
</script>

<style scoped lang="scss">
.model-title-css {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}
.list_wrap {
  margin-top: 20px;
}
.left-box {
  min-width: 220px !important;
  max-width: 350px !important;
  max-height: calc(100vh - 200px);
  border-right: 1px #e2e8ec solid;
  overflow: auto;
  p {
    cursor: pointer;
    font-size: 14px;
  }
}
.right-box {
  width: calc(100% - 220px);
  padding: 0 0 0 15px;
  flex-grow: 1;
}
.icon-a-wenjian1 {
  font-size: 26px;
}
</style>
